import React, { Component } from 'react'
import style from "./information.module.scss";
import header from '../../base/Header';

import {connect} from "react-redux";
import store from "../../Store";

const imgDefault = require("../../common/image/home/swiper01.jpg").default;

let message = {
	// 查询字段
	mid: "uuid",
	isdel:"0",
	buildtime:new Date(),
	// 发送者信息
	fromUid:"",
	fnickname:"",
	fhead_url:"",
	fstuAuth:"",
	// 接收者信息
	toUid:"",
	tnickname:"",
	thead_url:"",
	tstuAuth:"",
	// 信息内容
	type: "chat",
	message:"信息内容",
	sendtime:new Date(),
	readtime:new Date(),
	// 携带商品
	bid:"",
	cover:"",
	name:"",
	despcription:"",
	price:"",
	origin_price:"",
}

 let friend = {
  fid: "message.fromUid || message.toUid",
  fnickname: "message.fnickname || message.tnickname",
  head_url: "message.fhead_url || message.thead_url",
  lastMsgTime: "msgList[0].sendtime",
  stuAuth: "message.fstuAuth || message.tstuAuth",
  msgCount: "msgList[0].message",
  msgList:["message,message,message"],
}

// 消息中心
// 1、监听仓库的 消息队列 （监听）
// 2、分析消息队列，整理出 联系人列表，以及当前联系人是否未读度消息
// 3、渲染联系人列表
// 4、建立跳转连接

class Information extends Component {
    state={
        userinfo:{uid:""},
        msgList: [],
        friendList:[],
    }

    messagesTransform(meid){
        // let {messageList} = this.props;
        let {messageList} = store.getState();
        let friendList = [];
        messageList.forEach((message)=>{
            let target = friendList.find(it=>
                (it.fid == message.fromUid || it.fid == message.toUid) 
                && message.fid != meid
            );
            // console.log("target",target.fid);
            if(!target){
                let friend = {};
                if(message.fromUid == meid){
                    friend = {
                        fid: message.toUid,
                        fnickname: message.tnickname,
                        head_url: message.thead_url,
                        lastMsgTime: "msgList[0].sendtime",
                        stuAuth: message.tstuAuth,
                        msgList:[],
                    }
                }else{
                    friend = {
                        fid: message.fromUid,
                        fnickname: message.fnickname,
                        head_url: message.fhead_url,
                        lastMsgTime: "msgList[0].sendtime",
                        stuAuth: message.fstuAuth,
                        msgList:[],
                    }
                }
                friendList.push(friend);
            }
        });

        friendList.forEach((friendItem)=>{
            messageList.forEach(msgItem=>{
                if(msgItem.toUid == friendItem.fid || msgItem.fromUid == friendItem.fid){
                    friendItem.msgList.push(msgItem);
                }
            })
        })
        this.setState({friendList});
        setTimeout(()=>{
            console.log("fffff",friendList)
        },100)
    }

    // 跳转私聊
    goPrivateChat(friendInfo){
        let {userinfo, item} = this.state;
        if(!userinfo.uid) return alert("请先登录!");

        this.props.history.push({
            pathname:"/privateChat", 
            state:{
                toUid: friendInfo.fid,
                tnickname: friendInfo.fnickname,
                thead_url: friendInfo.head_url,
                tstuAuth: friendInfo.stuAuth,
            }
        })
    }

    componentDidMount(){
        let temp = localStorage.getItem("userList");
        if(!temp) return this.props.history.push("/login");
        let userinfo = JSON.parse(temp);
        this.setState({userinfo});

        // let {messageList} = store.getState();
        // console.log("----------->",messageList);
        this.messagesTransform(userinfo.uid);
    }
    render() {
        let friendItems = this.state.friendList.map((friend)=>{
            return (
                <div key={friend.fid} className={style["friend-item"]}
                    onClick={this.goPrivateChat.bind(this,friend)}
                >
                    <img className={style["user-head"]} src={"/apis/"+friend.head_url} />
                    <div className={style["msg-top"]}>
                        <h3 className={style["uname"]}>{friend.fnickname}</h3>
                        <p className={style["last-msg"]}>{friend.msgList[0].message}</p>
                    </div>
                    <div className={style["msg-bottom"]}>
                        <i className={style["last-time"]}>{
                            // new Date(friend.msgList[0].sendtime).toLocaleDateString()
                            friend.msgList[0].sendtime
                        }</i>
                        <i className={style["msg-count"]}>{friend.msgList.length}</i>
                    </div>
                </div>
            )
        });

        console.log("f",friendItems)
        
        return (
            <div className={style.message}>
                {header({title:"消息中心",history:this.props.history})}

                <div className={style["friend-list"]}>
                    {friendItems.length
                        ? friendItems 
                        : <div className={style["friend-blank"]} >
                            <i>~ 没有消息 ~</i>
                        </div>
                    }

                </div>
            </div>
        )
    }
}


const mapStateToProps = (state)=>{
    return {
        messageList: state.messageList
    };
}
const mapDispatchToProps= (dispatch)=>{
    return {
        addMessage:(message)=>{
            dispatch({type:"ADDMESSAGE",data:message})
        },
        clearMessage:()=>{
            dispatch({type:"CLEARMESSAGE"});
        },
        pullCMessage:(message)=>{
            dispatch({type: "PULLCMESSAGE",data: message})
        },
        clearCMessage:(message)=>{
            dispatch({type: "CLEARCMESSAGE", data: message})
        },
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(Information);